from syslogd.log.Event import Event
import time
import re
from syslogd.gui.eventlisteners.AlertsTabListener import AlertsTabListener

class Filter(object):
    
    def __init__(self, filtrs, interval, repeats):
        self.interval = interval
        self.repeats = repeats
        self.regexs = filtrs
        
        self.filters = []
        for fl in filtrs:
            self.filters.append(re.compile(fl))

    def match(self, string):
        for fl in self.filters:
            if(fl.match(re.escape(string)) != None):
                return True
        return False

    def canAddEvent(self, event):
        return self.match(event.getLog())
            
    def getRepeats(self):
        return self.repeats        

    def getInterval(self):
        return self.interval
            
    def __str__(self):
        return "Filter '" +  ', '.join(self.regexs) + "' with " + str(self.repeats) + " repeats is calling"
    
    

class Filters(object):

    def __init__(self):
        self.filters = {}
        self.logger = []
        
    def addFilter(self, filtr):
        self.filters[filtr] = []
        for event in self.logger:
            if filtr.canAddEvent(event):
                self.filters[filtr].append(event)            
       
    def removeFilter(self,filtr):
        if filtr in self.filters:
            del self.filters[filtr]
        
    def getLogs(self):
        return self.logger  
        
    def getFiltersKeys(self):
        return self.filters.keys()
        
    def getFilterLogs(self, filtr):
        return self.filters[filter]
    
    def getLoggerSize(self):
        return len(self.logger)
     
    def getFiltersSize(self):
        return len(self.filters)
  
    def getFilterLogsSize(self, filtr):
        return len(self.filters[filtr])
    
    def determineLog(self,log):
        event = Event(time.time(),log)
        self.logger.append(event)
        # add to view all tab
        for filtr in self.filters.keys():
            if filtr.canAddEvent(event):
                currentTime = time.time()
                events = self.filters[filtr]
                print events
                countAllert = 0
                for e in events:
                    if currentTime - e.getTime() < filtr.getInterval():
                        countAllert += 1
                print countAllert
                if countAllert >= filtr.getRepeats():
                    print filtr.__str__()
                    AlertsTabListener.getInstance().addLine(filtr.__str__())
                
                self.filters[filtr].append(event)
                print event.__str__() + " added to filter " + filtr.__str__()
                # check if alert
        
    def printFilters(self):
        print self.logger
        for filtr in self.filters.keys():
            print filtr
            for el in self.filters[filtr]:
                print "\t" + str(el)
